package com.lzy.pattern.proxy.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName: ProxyFactory
 * @Description: 代理工厂类
 * @Author: LiuZy
 * @Date: 2022/4/19 22:23
 * @Version: 1.0
 */
public class ProxyFactory implements MethodInterceptor {

    private TrainStation trainStation = new TrainStation();

    public TrainStation getProxyObject(){

        //创建Enhancer对象，类似于JDK动态代理的Proxy类
        Enhancer enhancer = new Enhancer();
        //设置父类的字节码对象
        enhancer.setSuperclass(TrainStation.class);
        enhancer.setCallback(this);
        TrainStation proxy =  (TrainStation)enhancer.create();

        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("代理点收取了一些手续费（CGLIB动态代理）");
        Object result = method.invoke(trainStation, objects);
        return result;
    }
}